<template>
  <div class="image" v-loading="loading">
    <header class="image-head">
      <div class="head-tabs"  >

        <div class="custom-tab">
            <span :class="{'active-1': activeName === '全部'}" @click="handleClick('全部', '')">全部</span>
            <span :class="{'active-1': activeName === i.name}" v-for="i in imgList" :key="i.id" @click="handleClick(i.name, i.id)">{{i.name}}</span>
            <!-- <span :class="{'active-1': activeName === '牙周检查'}" @click="handleClick('牙周检查')">牙周检查</span>
            <span :class="{'active-1': activeName === '治疗计划'}" @click="handleClick('治疗计划')">治疗计划</span> -->
        </div>
      </div>
      <div class="head-btns">
        <el-button class="btn-2" @click="delImageFn" v-jurisdiction="'customer:sick:image:del'">删除图片</el-button>
        <el-button class="btn-2" @click="handleBatchExport">批量导出</el-button>
        <el-button class="btn-1" @click="openUpload" v-jurisdiction="'customer:sick:image:add'">上传影像</el-button>
      </div>
    </header>

    <div class="image-content">
      <!-- 全部 -->
      <div class="image-type-template" v-show="activeName === '全部'" >
          <template v-if="imageList.length">
              <div v-for="(item, idx) in imageList" :key="item.id">
                <div class="image-title">
                <div class="date">{{item.day || '暂无'}}</div>
                <div class="address">{{ user.deptName || '暂无'}}</div>
                <div class="all-check">
                  <!-- <el-checkbox v-model="allChecked" @change="AllChecked">导出当前全部影像</el-checkbox> -->
                </div>
                </div>
                
                <div class="image-content">
                  <div class="image-bg"  v-for="(img, index) in item.list" :key="img.id">
                    <el-checkbox v-model="img.checked" class="check-position" :true-label="img.url" @change="getChecked($event,idx, index, img)">
                      
                      <el-image
                        class="image-position"
                        style="width: 100px; height: 100px"
                        :src="img.url"
                        :preview-src-list="srcList[idx]"
                        :initial-index="index"
                        fit="cover">
                        <template #error>
                            <div class="image-slot">
                              <el-icon><Picture /></el-icon>
                            </div>
                          </template>
                        </el-image>
                    </el-checkbox>
                  </div>
                </div>
              </div>
              
            </template>
          <el-empty v-else description="暂无图片"></el-empty>
      </div>
      <div class="image-type-template"  v-for="i in imgList" :key="i.id" v-show="activeName === i.name">
          <template v-if="imageList.length">
              <div v-for="(item, idx) in imageList" :key="item.id">
                <div class="image-title">
                <div class="date">{{item.day || '暂无'}}</div>
                <div class="address">{{ user.deptName || '暂无' }}</div>
                <div class="all-check">
                  <!-- <el-checkbox v-model="allChecked" @change="AllChecked">导出当前全部影像</el-checkbox> -->
                </div>
                </div>
                <div class="image-content">
                  <div class="image-bg"  v-for="(img, index) in item.list" :key="img.id">
                    <el-checkbox v-model="img.checked" class="check-position" :true-label="img.url" @change="getChecked($event, idx, index, img)">
                      <el-image
                        class="image-position"
                        style="width: 100px; height: 100px"
                        :src="img.url"
                        :preview-src-list="srcList[idx]"
                        :initial-index="index"
                        fit="cover"></el-image>
                    </el-checkbox>
                  </div>
                </div>
              </div>
              
            </template>
          <el-empty v-else description="暂无图片"></el-empty>
      </div>

    </div>
  </div>

  <zdialog 
        @handleClose="close" 
        v-model="dialogVisible" 
        :btnData="btnData"
        title="上传影像"
        >
			<template #body>
        <div class="tem-item" style="display: flex; align-items: center">
          <span class="label">上传时间</span>
          <div>
            <el-date-picker
              v-model="createTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择时间"
            />
          </div>
        </div>
        <div class="tem-item">
          <span class="label">影像类型</span>
          <el-select v-model="imgType"  class="select-2" placeholder="请选择">
            <el-option
              v-for="item in imgList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div class="tem-item">
          <span class="label">对应病历</span>
          <el-select v-model="recordItem"  class="select-2" placeholder="请选择">
            <el-option
              v-for="item in recordList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div class="tem-item">
          <span class="label">图片</span>
          <!-- <el-upload
            style="width: 200px"
            class="avatar-uploader"
            
            action="https://www.jxcloudlight.com/chain/fileUpLoad/uploadImage"
            :headers="{ token: token}"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            name="fileUpload"
          >
            <img v-if="imgUrl" :src="imgUrl" class="avatar">
            <span v-else class="upload-text">点击上传文件</span>
          </el-upload> -->
          
          <!-- http://180.184.96.73/chain/fileUpLoad/uploadImage -->
          <el-upload
              ref="uploadRef"
              style="display: flex"
              action="http://180.184.96.73/chain/fileUpLoad/uploadImage"
              list-type="picture-card"
              multiple
              :headers="{ token: token}"
              name="fileUpload"
              :on-preview="handlePictureCardPreview"
              :on-success="handleAvatarSuccess"
              :on-remove="handleRemove"
            >
              <el-icon><Plus /></el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisibleImge">
            <img style="width: 100%;height: 600px" w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </div>
        
			</template>
		</zdialog>
</template>

<script lang="ts">
import { Picture } from '@element-plus/icons-vue'
import { defineComponent, reactive, toRefs, ref, onMounted, watch } from "@vue/runtime-core";
import { delImageAPi, addImageListAPi } from "../../../api/common"
import zdialog from "../../../components/dialog/dialog.vue";
import useUser from "../../../hook/user";

import {Option} from "../../../types"
import { getNowDate } from "../../../utils/nowDate"

import useRequet, { RespData } from "../../../hook/network"
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

import type { UploadProps, UploadUserFile } from 'element-plus'
import { useRoute } from 'vue-router';



type ImageList = {
  url: string,
  id: number,
  day?: string,
  checked: boolean,
  list: any[]
}
export default defineComponent({
  name: 'Image',
  components: {
    zdialog,

    Picture,
    Plus
  },
  setup(props) {
    const user = useUser();
    const route = useRoute()
    const request = useRequet({ path: "" });
    let id = route.params.id
    watch(() => route.params.id, (newId, prevId) => {
      id = newId
      
      if(newId) {
        getList('')
        getImgList()
      }
    })
    let token = useUser().getToken()
    const list = reactive({
      createTime: getNowDate(),
      activeName: '全部',
      checked: '',
      allChecked: false,
      imageList:[] as ImageList[],

      imgList: [] as Option[], //图片下拉
      imgType: '',
      recordList: [] as Option[], // 病历下拉
      recordItem: '',
      // imgUrl: '',
      imgUrl: [] as any[],
      fileName: '',
      loading: false,
      checkedImg: [],
      srcList: <string[][]>[],
      initIndex: 0,

      delImgId: <number[]>[]

    })

    const uploadRef = ref<any>(null)
    onMounted(() => {
      getList('')
      getImgList()
    })

    const handleClick = (val: string, id: number | string) => {
      list.activeName = val
      if(list.activeName === '全部') {
        getList('')
      } else {
        getList(id)
      }
      
    }
    const getChecked = (val:string, parenIdx:number, index: number, data: any) => {
      list.initIndex = index;
      console.log('执行了哦', index, list.initIndex)
      
      let { id } = data;
      list.delImgId.push(id)
    
      if(!val) {
        
        list.delImgId = list.delImgId.filter(i => i != id)
      }

    }

    // 删除图片
    const delImageFn = async() => {
      if(list.delImgId.length > 1) {
        ElMessage.warning('一次只能删除一张图片哦')
        return false
      } else if (!list.delImgId.length) {
        ElMessage.warning('您还未选择要删除的图片哦')
        return false
      } else {
        let id = list.delImgId[0];
        let res:any = await delImageAPi({}, id);
        if(res.code !== 0) return ElMessage.error(res.msg || '获取信息失败')
        ElMessage.success('删除成功')
        list.delImgId = []
        getList('')
      }
      
    }

    const AllChecked = (val:boolean) => {
    }

    

    let dialogVisible = ref(false)
    const btnData = [
      {
        name: '上传',
				func: (data:boolean) => {
							console.debug('上传',data)
              console.log(list.imgUrl)
              if(list.imgUrl.length > 0) {
                fileLoad()
              } else {
                ElMessage.warning('还未上传图片')
                return false
              }
              
				}
      }
    ]
    const fileLoad = async() => {
      let params = {
        customerId: Number(id),
        images: list.imgUrl,
        remark: '',
        medicalHistoryId: list.recordItem,
        typeId: list.imgType,
        createTime: list.createTime
      }
      console.log(params)
      list.loading = true
      let res: any = await addImageListAPi(params);
      if(res.code !== 0) return ElMessage.error(res.msg || '获取信息失败')
        ElMessage.success('添加成功')
        dialogVisible.value = false
        list.loading = false

        getList('')

        close()
    }

    const openUpload = () => {
      console.log('点击了')
      dialogVisible.value = true
      getRecordList()
    }

    const close = () => {
      console.log('执行close')
      // 清空上传
      uploadRef.value.clearFiles();

      dialogVisible.value = false;
      list.imgType = ''
      list.recordItem = ''
      list.imgUrl = []
      list.fileName = ''
    }

    const getList = (typeId: number | string) => {
      list.loading = true
      list.srcList = []
      request.sendRequest({
        address: 'sick/image/getImageList',
        params: {
          customerId: Number(id),
          typeId: typeId
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
          console.log(resp.data)
          
          resp.data && resp.data.forEach((item: any, index:number) => {
            list.srcList[index] = resp.data[index].list.map((c:any) => c.url)
            item.list.forEach((i: any) => {
              i.checked = false
            })
          })
          // 全部图片
          list.imageList = resp.data
          list.loading = false

          console.log(list.imageList, list.srcList)
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      }) 
    }
    

    // 获取图片下拉
    const getImgList = () => {
      list.loading = true
      request.sendRequest({
        address: 'sick/image/getCustomerImageType',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          console.log(resp.data)
          list.imgList = resp.data
          list.loading = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      }) 
    }
    
    
    // 获取病历下拉
    const getRecordList = () => {
      request.sendRequest({
        address: 'sick/history/getHistorySelect',
        params: {
          customerId: Number(id)
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          console.log(resp.data)
          list.recordList = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      }) 
    }

    const handleAvatarSuccess = (res: any, file: any) => {
      console.log(res, file)
      // console.log(file.name)
      // list.fileName = file.name
      // list.imgUrl = res.data.url
      list.imgUrl.push({
        name: file.name,
        url: res.data.url,
        localPath: res.data.localPath
      })

      
    }

    const dialogImageUrl = ref('')
    const dialogVisibleImge = ref(false)
    const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
      console.log(uploadFile, uploadFiles)
      list.imgUrl = []
      uploadFiles.map((i:any) => {
        list.imgUrl.push({
          name: i.name,
          localPath: i.response.data.localPath,
          url: i.response.data.url,
        })
      })
    }

    const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
      console.log('handlePictureCardPreview', uploadFile)
      dialogImageUrl.value = uploadFile.url!
      dialogVisibleImge.value = true
    }

    const handleBatchExport = () => {
      ElMessage('功能还在完善,敬请期待......');
    }
    
    return {
      ...toRefs(list),
      user,
      handleClick,
      getChecked,
      AllChecked,
      openUpload,
      close,
      btnData,
      dialogVisible,
      handleAvatarSuccess,
      getList,
      getImgList,
      handleBatchExport,

      uploadRef,
      delImageFn,

      dialogImageUrl,
      dialogVisibleImge,
      handleRemove,
      handlePictureCardPreview,

      request,
      token
    }
  }

})
</script>

<style lang="scss" scoped>
.image {
  height: 100%;
  display: flex;
  flex-direction: column;
  .image-head {
    height: 40px;
    line-height: 40px;
    position: relative;
    .head-btns {
      position: absolute;
      top: 0px;
      right: 10px;
    }
    .head-tabs {
      .tabs-pane {
        
      }

      .custom-tab {
        height: 100%;
        font-size: $fontSize-1;
        border-bottom: 1px solid $mainColor;
        background: $a2-Color;
        & > span {
          padding: 10px 20px;
          cursor: pointer;
          position: relative
        }

        & > span::before {
          content: '';
          width: 1px;
          height: 100%;
          background: $a10-Color;
          position: absolute;
          right: 0;
          transform: scaleY(.5);
        }
      }
    }
  }

  .image-content {
    padding: 10px;
    overflow: scroll;
    flex: 1;
    .image-type-template {
        position: relative;
        display: flex;
        flex-direction: column;
        .image-title {
          padding-left: 10px;
          box-sizing: border-box;
          display: flex;
          font-size: $fontSize;
          align-items: center;
          .date {
            position: relative;
            padding-left: 10px;
          }
          .date::before {
            content: "";
            display: block;
            width: 3px;
            position: absolute;
            height: 100%;
            background: $mainColor;
            top: 0;
            left: 0;
            // transform: scaleY(.3);
          }

          .address {
            padding: 0 10px 0 10px;
          }
        }
        .image-content {
          display: flex;
          flex-wrap: wrap;
          .image-bg {
            position: relative;
            background: #e9e9e9;
            width: 120px;
            height: 120px;
            margin: 10px 0 0 0;
            .check-position {
              position: absolute;
              top: 0;
              left: 0px;
              padding-left: 12px;
            }
            .image-position {
              position: absolute;
              top: 10px;
              left: 10px;
              display: inline-block;
            }
          }
          .image-bg:first-child {
            margin-left: 10px;
          }
        }
    }
  }
}

.tem-item {
  padding: 5px 10px;
  .label {
    font-size: 14px;
    font-weight: 600;
    color: #000;
    padding-right: 15px;
  }
}
:deep(.el-upload) {
  width: 200px
}

.avatar-uploader {
  // width: 200px;
  height: 100px;
  border: 1px solid $a7-Color;
  position: relative;
  border-radius: $radius-1;
  .avatar {
    width: 100%;
    height: 100px;
  }
  .upload-text {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: $a7-Color;
  }
}



</style>